//
//  BuyCarsViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/7/18.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "BuyCarsViewController.h"
#import "CarGooodsTableViewCell.h"
#import "SZLTabBarViewController.h"
#import "CarShopHeaderView.h"
#import "CarPayToolBar.h"
#import <Masonry.h>
#import "SingleNetService.h"
#import "SZLAccountHelper.h"
#import "BuyCarModel.h"
#import "UIAlertView+Entension.h"
#import "SZLSureSingleViewController.h"
#import "MBProgressHUD+MJ.h"
#import "SZLWebViewController.h"
#import "SZLNavigationController.h"
#import "ConGoodsDetailController.h"

@interface BuyCarsViewController ()<UITableViewDataSource,UITableViewDelegate,CarPayToolBarDelegate,CarGooodsTableViewCellDelegate,CarShopHeaderViewDelegate,SZLWebViewControllerDelegate>

@property (nonatomic,weak) UIButton *editBtn;
@property (nonatomic,strong) UITableView *sourceTab;
@property (nonatomic,strong) NSMutableArray *buyCars;
@property (nonatomic,weak) UIBarButtonItem *rightItem;
@property (nonatomic,weak) CarPayToolBar *toolBar;
@property (nonatomic,strong) NSMutableArray *deletes;//要删除的订单
@property (nonatomic,strong) NSMutableArray *payGoods;//去付款的商品订单号
@property (nonatomic,strong) NSArray *payModels;//确认订单后返回的商品模型

@end

@implementation BuyCarsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.navigationItem.title = @"购物车";
    //[self setNavi];右上角编辑
    [self setView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.toolBar.isSelected = NO;
    [self getBuyCarList];
}
- (void)setNavi
{
    UIButton *editBtn = [[UIButton alloc]init];
    [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
    [editBtn setTitle:@"完成" forState:UIControlStateSelected];
    [editBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    editBtn.titleLabel.font = Font(15);
    [editBtn addTarget:self action:@selector(editClick:) forControlEvents:UIControlEventTouchUpInside];
    self.editBtn = editBtn;
    [editBtn sizeToFit];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:editBtn];
}
- (void)setView
{
    CarPayToolBar *toolBar = [[CarPayToolBar alloc]init];
    toolBar.delegate = self;
    self.toolBar = toolBar;
    [self.view addSubview:toolBar];
    [self.toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
        make.right.equalTo(self.view.mas_right);
    }];
    [self.view addSubview:self.sourceTab];
    [self.sourceTab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.toolBar.mas_top);
        make.right.equalTo(self.view.mas_right);
    }];
}
- (void)editClick:(UIButton *)btn
{
    btn.selected = !btn.selected;
    self.toolBar.isEditing = btn.selected;
    [self needsSelectAll:NO];
    self.toolBar.isSelected = NO;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    BuyCarModel *carModel = self.buyCars[section];
    if (carModel.productList.count<1) return 0.01;
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    BuyCarModel *carModel = self.buyCars[section];
    if (carModel.productList.count<1) return nil;
    CarShopHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([CarShopHeaderView class])];
    header.model = carModel;
    header.delegate = self;
    return header;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.buyCars.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    BuyCarModel *carModel = self.buyCars[section];
    return carModel.productList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CarGooodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CarGooodsTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BuyCarModel *carModel = self.buyCars[indexPath.section];
    cell.model = carModel.productList[indexPath.row];
    cell.delegate = self;
    return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    BuyCarModel *carModel = self.buyCars[indexPath.section];
    NormalShopGoodsModel *goodsModel = carModel.productList[indexPath.row];
    [self buyCarDelete:@[goodsModel.productNo]];//删除请求
    [carModel.productList removeObjectAtIndex:indexPath.row];
    if (carModel.productList.count == 0) {//当一个分组只剩最后一行时 要删除整个分组 否则崩溃
        [self.buyCars removeObject:carModel];
        [self.sourceTab deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
    }
    [self.sourceTab deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BuyCarModel *carModel = self.buyCars[indexPath.section];
    NormalShopGoodsModel *goodsModel = carModel.productList[indexPath.row];
    ConGoodsDetailController *goodsVc = [[ConGoodsDetailController alloc]init];
    goodsVc.productNo = goodsModel.productNo;
    [self.navigationController pushViewController:goodsVc animated:YES];
}
- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc]init];
        _sourceTab.dataSource = self;
        _sourceTab.delegate = self;
        _sourceTab.backgroundColor = RGBColor(239, 239, 244);
        _sourceTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([CarGooodsTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([CarGooodsTableViewCell class])];
        [_sourceTab registerClass:[CarShopHeaderView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([CarShopHeaderView class])];
        _sourceTab.tableFooterView = [[UIView alloc]init];
    }
    return _sourceTab;
}
#pragma mark ---CarPayToolBarDelegate
- (void)carPayToolBarClick:(ToolBarType)type select:(BOOL)isSelect
{
    switch (type) {
        case ToolBarTypeSelectAll:
        {
            [self needsSelectAll:isSelect];
            self.toolBar.realMoney = [self calculateSelectMoney];
        }
            break;
        case ToolBarTypePay:
        {
            NSArray *payGoods = [self getPayGoodsList];
            if (self.buyCars.count == 0) {
                [MBProgressHUD showError:@"请先添加商品" toView:self.view];
                return;
            }
            if (payGoods.count == 0) {
                [MBProgressHUD showError:@"请选择要付款的商品" toView:self.view];
                return;
            }
            [self buyCarToPay:payGoods];
        }
            break;
        case ToolBarTypeDelete:
        {
            NSArray *deleteGoods = [self getDeleteList];
            if (deleteGoods.count == 0) {
                [MBProgressHUD showError:@"请选择要删除的商品" toView:self.view];
                return;
            }
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"要批量删除商品吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
            __weak typeof(self) weakSelf = self;
            [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
                if (btnIndex == 1) {
                    [weakSelf buyCarDelete:deleteGoods];
                }
            }];
            [alert show];
        }
            break;
    }
}
#pragma mark ----------------CarShopHeaderViewDelegate-----------
- (void)carShopHeaderViewSelect:(BuyCarModel *)model
{
    self.toolBar.realMoney = [self calculateSelectMoney];
    for (NormalShopGoodsModel *normalModel in model.productList) {
        normalModel.isSelect = model.isSelect;
    }
    !model.isSelect?(self.toolBar.isSelected = NO):0;
    model.isSelect?(self.toolBar.isSelected = [self lookSelectAll]):0;
    [self.sourceTab reloadData];
    self.toolBar.realMoney = [self calculateSelectMoney];
}

#pragma mark ----------------CarGooodsTableViewCellDelegate-----------
- (void)CarGooodsTableViewCellBtnAction:(AmountType)type label:(UILabel *)countLab model:(NormalShopGoodsModel *)model
{
    switch (type) {
        case AmountTypeAdd:
        case AmountTypeMinus:
        {
            [self buyCarUpdateType:type label:countLab model:model];
        }
            break;
        case AmountTypeSelect:
        {
            !model.isSelect?(self.toolBar.isSelected = NO):0;
            model.isSelect?(self.toolBar.isSelected = [self lookSelectAll]):0;
            if (model.isSelect&&!model.superModel.isSelect) {
                model.superModel.isSelect = YES;
                [self.sourceTab reloadData];
            }else if (!model.isSelect&&model.superModel.isSelect){
                //如果header下面cell没有选中的 header也取消选中
                for (NormalShopGoodsModel *goodsModel in model.superModel.productList) {
                    if (goodsModel.isSelect) {
                        model.superModel.isSelect = YES;
                        break;
                    }else{
                        model.superModel.isSelect = NO;
                    }
                }
                //if (model.superModel.isSelect) return;//如果有选中的不操作
                [self.sourceTab reloadData];
            }
        }
            break;
        default:
            break;
    }
    self.toolBar.realMoney = [self calculateSelectMoney];
}
#pragma mark --------------------请求相关--------------------
- (void)buyCarDelete:(NSArray*)deletes
{
    self.toolBar.isSelected = NO;
    self.editBtn.selected = NO;
    self.toolBar.isEditing = NO;
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"productNos"] = [deletes componentsJoinedByString:@"#"];
    [self showClearBgWaiter];
    [SingleNetService buyCarDeleteParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [self getBuyCarList];//重新请求获取列表
            if (self.countChangedBlock) {
                self.countChangedBlock();
            }
        }else{
            [MBProgressHUD showError:msg toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if ([msg isEqualToString:NoLoginError]) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    SZLTabBarViewController *barVc = (SZLTabBarViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
                    barVc.selectedIndex = 0;
                    [SZLAccountHelper clearAlreadyInfo];
                    [SZLAccountHelper shouldLogin];
                }
            });
        }
    }];
}
- (void)buyCarUpdateType:(AmountType)type label:(UILabel *)countLab model:(NormalShopGoodsModel*)model
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"productNo"] = model.productNo;
    parame[@"optionType"] = @(type);
    [self showClearBgWaiter];
    [SingleNetService buyCarUpdateParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            (type == 1)?model.productInShopCarCount++:model.productInShopCarCount--;
            countLab.text = [NSString stringWithFormat:@"%zd",model.productInShopCarCount];
            [self.sourceTab reloadData];
            self.toolBar.realMoney = [self calculateSelectMoney];
            if (self.countChangedBlock) {
                self.countChangedBlock();
            }
        }else{
            [MBProgressHUD showError:msg];
        }
    }];
}
- (void)getBuyCarList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showClearBgWaiter];
    [SingleNetService buyCarListParame:parame response:^(BOOL success, NSString *msg,NSArray *buyCarGoods) {
        [self hideWaiter];
        [self hideRequestAgainView];
        [self.buyCars removeAllObjects];
        self.toolBar.realMoney = 0;
        if (success) {
            if (buyCarGoods.count==0) {
                [self showNoDataView:self.sourceTab.frame title:@"购物车暂无商品,请到商城添加"];
                self.editBtn.hidden = YES;
                return ;
            }else{
                self.editBtn.hidden = NO;
                [self hideNoDataView];
                [self.buyCars removeAllObjects];
                [self.buyCars addObjectsFromArray:buyCarGoods];
                self.toolBar.goods = self.buyCars;
                [self.sourceTab reloadData];
            }
        }else{
            if ([msg isEqualToString:NoNetworkStatus]) {
                [self showRequestAgainView:@selector(getBuyCarList)];
            }
        }
    }];
}
- (void)buyCarToPay:(NSArray *)payArr
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"productNos"] = [payArr componentsJoinedByString:@"#"];
    [self showWaiter];
    [SingleNetService buyCarToPayParame:parame response:^(BOOL success, NSString *msg,NSArray *payModels) {
        [self hideWaiter];
        if (success) {
            if (payModels.count == 0) return;
            self.payModels = payModels;
            [self jumpToSureSingle];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
//跳确认页面
- (void)jumpToSureSingle
{
    SZLSureSingleViewController *sureVc = [[SZLSureSingleViewController alloc]init];
    sureVc.payModels = self.payModels;
    [self.navigationController pushViewController:sureVc animated:YES];
}
//跳协议
- (void)jumpToBuyProtocol
{
    SZLWebViewController *webVc = [[SZLWebViewController alloc]init];
    SZLNavigationController *naviVc = [[SZLNavigationController alloc]initWithRootViewController:webVc];
    webVc.navigationItem.title = @"购买协议";
    webVc.requestStr = [NSString stringWithFormat:@"%@/agreement/buy/normal/product",PublicServer];
    webVc.type = ProtocolTypeBuy;
    webVc.delegate = self;
    [self presentViewController:naviVc animated:YES completion:nil];
}
#pragma  mark ----------SZLWebViewControllerDelegate------------
- (void)szlWebViewControllerPop
{
    [self dismissViewControllerAnimated:YES completion:^{
        [self jumpToSureSingle];
    }];
}
#pragma mark --------------对模型进行操作---------------
- (NSArray *)getPayGoodsList
{
    [self.payGoods removeAllObjects];
    for (BuyCarModel *buyCarModel in self.buyCars) {
        for (NormalShopGoodsModel *goodsModel in buyCarModel.productList) {
            if (goodsModel.isSelect) {
                [self.payGoods addObject:goodsModel.productNo];
            }
        }
    }
    return self.payGoods;
}
//获取要删除的模型
- (NSArray *)getDeleteList
{
    [self.deletes removeAllObjects];
    for (BuyCarModel *buyCarModel in self.buyCars) {
        for (NormalShopGoodsModel *goodsModel in buyCarModel.productList) {
            if (goodsModel.isSelect) {
                [self.deletes addObject:goodsModel.productNo];
            }
        }
    }
    return self.deletes;
}
//全部选中或取消
- (void)needsSelectAll:(BOOL)isSelect
{
    for (BuyCarModel *carModel in self.buyCars) {
        carModel.isSelect = isSelect;
        for (NormalShopGoodsModel *goodsModel in carModel.productList) {
            goodsModel.isSelect = isSelect;
        }
    }
    [self.sourceTab reloadData];
}
//计算选中价格
- (float)calculateSelectMoney
{
    float realMoney = 0;
    for (BuyCarModel *carModle in self.buyCars) {
        for (NormalShopGoodsModel *goodModle in carModle.productList) {
            if (goodModle.status == 1&&goodModle.isSelect) {
                realMoney += goodModle.price*goodModle.productInShopCarCount;
            }
        }
    }
    return realMoney;
}
//是否全部选中
- (BOOL)lookSelectAll
{
    for (BuyCarModel *carModle in self.buyCars) {
        if (!carModle.isSelect) {
            return NO;
        }
        for (NormalShopGoodsModel *goodModle in carModle.productList) {
            if (!goodModle.isSelect) {
                return NO;
            }
        }
    }
    return YES;
}
- (NSMutableArray *)buyCars
{
    if (!_buyCars) {
        _buyCars = [NSMutableArray array];
    }
    return _buyCars;
}
- (NSMutableArray *)deletes
{
    if (!_deletes) {
        _deletes = [NSMutableArray array];
    }
    return _deletes;
}
- (NSMutableArray *)payGoods
{
    if (!_payGoods) {
        _payGoods = [NSMutableArray array];
    }
    return _payGoods;
}
@end
